<?php

namespace app\controller;

use app\message;
use app\BaseController;
use app\model\ClueCommunicateRecord;
use app\model\ClueMobile;
use app\model\CluePerson;
use app\model\CluePersonAllocationRecord;
use app\model\CluePersonCertificate;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\SystemMenuDataPower;
use app\model\SystemOperateLog;
use app\model\UnitInfo;
use app\model\User;
use app\model\WorkPlan;
use app\Request;
use app\service\Certificate;
use app\service\CustomField;
use app\service\Power;
use app\service\RedisService;
use app\service\System;
use app\stateData;
use app\validate\Clue;
use app\validate\Enterprise;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;
use app\validate\ClueEnterprise as ClueEnterpriseValidate;

class ClueEnterprise extends BaseController
{
    private $enterPriseType = 2;
    /**
     * 线索库 企业库
     */

    //个人查询企业列表
    public function getPersonEnterpriseList(
        \app\model\ClueEnterprise   $cent,
        Request                     $request,
        Power                       $power,
        Certificate                 $certificate,
        \app\service\Order          $orderSer,
        \app\service\ClueEnterprise $clueEnterprise,
        \app\service\Clue $clueSer,
        CustomField $customField
    ){
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $aliasId = $request->get('aliasId');
        $type = $request->get('type') ?: 1;
        $uid = $request->param('user_login_id');
        $param = $request->get();

        $validate = new ClueEnterpriseValidate();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $clueEnterprise->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);
        $uid_ids = $cent->getPersonIds($uid, $type);
        $ids = handlePersonIds($uid_ids, $ids, $flag);

        $result = $certificate->arrMobile($cent->getPersonListModel($uid, $type, $pageNum, $page, $ids));

        //获取企业订单个数
        $result = $clueSer->enterData($orderSer->getEnterOrderCountNum($result, $uid),$uid);

        foreach($result as $key => $value){
            $result[$key] = $customField->listCustomFieldHandle($value);
        }

        //筛选已合作 未合作
        if ($param['status'] == 1 || $param['status'] == 2){
            foreach ($result as $ak => $item) {
                if ($item['status']['id'] != $param['status']){
                    unset($result[$ak]);
                }
            }
        }

        $pages['total'] = $cent->getPersonCountModel($uid, $type, $ids);

        $pages['pageNumber'] = $pageNum;

        return ReJson(
            message::$SUCC_CODE,
            message::$SUCC_SELECT_DATA,
            [
                'data' => $clueSer->enterData ($result,$uid),
                'power' => $fieldListTree
            ],
            $pages
        );
    }

    //管理查询企业列表
    public function getManageEnterpriseList(
        Request                     $request,
        \app\model\ClueEnterprise   $cent,
        User                        $user,
        Power                       $power,
        SystemMenuDataPower         $dataPower,
        \app\service\User           $userService,
        Certificate                 $certificate,
        \app\service\Order          $orderSer,
        \app\service\ClueEnterprise $clueEnterprise,
        \app\service\Clue $clueSer,
        CustomField $customField,
        \app\service\SystemMenuDataPower $dataPowerServer,
        RedisService $redisService
    ){

        $aliasId = $request->get('aliasId');

        $uid = $request->get('user_login_id');

        $param = $request->get();

        $page = $request->get('page') ?: 0;
        //查询电销部还是网销部
        $type = $request->get('type') ?: 1;

        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $validate = new ClueEnterpriseValidate();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }

        $flag = flagStatus($param);
        $ids = $clueEnterprise->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        //查询用户数据范围
        $range = $power->getUserDataRange($uid);

        //根据条件查询用户范围
        $data = $dataPowerServer->getOpenSeaPower($uid);
        $uid_ids = $cent->getManageListIds($range, $type,$data,$param);

        $ids = handlePersonIds($uid_ids, $ids, $flag);

        $resultId = $cent->getManageListModel($range, $page, $type, $pageNum, $ids);

        $result = $redisService->getEnterData(page($resultId,$page,$pageNum,'','',false),$uid);

        //获取企业订单个数
//        $result = $orderSer->getEnterOrderCountNum($result, $uid);

        foreach($result as $key => $value){
            $result[$key] = $customField->listCustomFieldHandle($value);
        }

        //筛选已合作 未合作
        if ($param['status'] == 1 || $param['status'] == 2){
            foreach ($result as $ak => $item) {
                if ($item['status']['id'] != $param['status']){
                    unset($result[$ak]);
                }
            }
            $result = array_values ($result);
        }

        $pages['total'] = $cent->getManageCountModel($range, $type,$ids);
        $pages['pageNumber'] = $pageNum;

        return ReJson(
            message::$SUCC_CODE,
            message::$SUCC_SELECT_DATA,
            [
                'data' => $result,
                'power' => $fieldListTree
            ],
            $pages
        );
    }

    //查看企业详情
    public function getEnterPriseDetails(
        Request                    $request,
        \app\model\ClueEnterprise $enterprise,
        ClueCommunicateRecord      $comRecord,
        ClueMobile                 $mobModel,
        CluePersonAllocationRecord $allocationRecord,
        OrderEnterpriseCompany     $company,
        OrderEnterpriseExchange $exchange,
        OrderEnterpriseCertificateBusiness $business,
        Power $power,
        CustomField $customField,
        \app\service\ClueEnterprise $clueEnterprise
    ){
        $id = $request->get('id');
        //是否是查询下一条信息
        $next = $request->get ('next') || 0;
        $isPower = $request->get('is_power') ?: 0;
        $uid = $request->get('user_login_id');
        $type = $request->get ('type')?:1; //1注册企业 2合作伙伴

        $param = $request->get();

//        $validate = new ClueEnterpriseValidate();
//        if (!$validate->check($param)) {
//            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
//        }
        $flag = flagStatus($param);
        $ids = $clueEnterprise->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;

        $uid_ids = $enterprise->getPersonIds($uid, $type);
        $ids = handlePersonIds($uid_ids, $ids, $flag);

        $dataId = $enterprise->getOrderDataIdModel($ids);

        //查询数据库最大ID值
        $maxId = $enterprise->getMaxIdModel();

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        if ($next){
            while (true){

                $daPosition = array_search ($id,$dataId);

                if (is_numeric ($daPosition)){
                    $daPosition++;
                    //如果要搜索下标值大于全部下标 则false
                    if($daPosition >= count ($dataId)){
                        $id  = '';
                        break;
                    }
                    $id = $dataId[$daPosition];
                    break;
                }
//                if ($id > 1){
//                    $id--;
//                    //查询是个人详情 还是管理详情
//                    if ($isPower == 1) {
//                        $nextData = Db::table('clue_enterprise')->where('id=' . $id . ' and is_del=0 and f_uid=' . $uid .' and type ='.$type)->find();
//                    } elseif ($isPower == 2) {
//
//                        $userData = $power->getUserDataRange($uid);
//                        $idArr = implode($userData);
//                        $nextData = Db::table('clue_enterprise')->where('id=' . $id . ' and is_del=0 and type ='.$type)->whereIn('f_uid', $idArr)->find();
//                    }
//                    if (!empty($nextData)){
//                        $id = $nextData['id'];
//                        break;
//                    }
//                }else{
//                    break;
//                }
            }
        }
        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$SELECT_INFO_ERR);

        $result['data'] = $enterprise->getIdInfo($id);
        //处理自定义字段
        $result['custom'] = $customField->detailsCustomFieldHandle($result['data']['custom']);

        //沟通记录
        $result['comReList'] = $comRecord->getPersonComRecordModel($id, $this->enterPriseType);

        //查询联系电话信息
        $result['mobileInfo'] = $mobModel->getPersonIdMobileModel($id, $this->enterPriseType);
        //生命周期
        $result['allReList'] = $allocationRecord->getPersonCycleModel($id, $this->enterPriseType);

        //订单字段模板
        $zszcField = $power->getUserFieldPower('ddzszc', $request->param('user_login_id'));//证书注册
        $dzField = $power->getUserFieldPower('ddzszcdz', $request->param('user_login_id'));//倒证
        $zsblField = $power->getUserFieldPower('ddzsbl', $request->param('user_login_id'));//证书办理

        //查询企业关联订单信息
        //先查询企业证书注册订单
        $comData = $company->getEnterpriseName($result['data']['enterprise_name']);
        //给所有证书注册添加字段
        $data = [];
        foreach ($comData as $key => &$comDatum) {
            //ddzszc
//            $comDatum['leixing'] =  '证书注册';
            foreach ($comDatum as $k =>$item) {
                //如果是获取器数组 则只去text

                //如果是获取器数组 则只去text
                if (is_array ($item)){
                    if (isset($item['text'])){
                        $item = $item['text']?:'';
                    }
                }

                $data[$key]['id'] = $comDatum['id'];
                $data[$key]['bh'] = $comDatum['certificate_code'];
                $data[$key]['create_date'] = $comDatum['create_date'];
                $data[$key]['leixing'] = '证书注册';
//                print_r ($k);
//                echo PHP_EOL;
                if ($k == 'status'){
                    $data[$key]['status'] = $item;
                }
                foreach ($zszcField as $zszciItem) {
                    //如果模板字段等于订单详情字段 拼接字段name
                    if ($k == $zszciItem['alias_field_id']){
                        if (!empty($zszciItem['name'])){
                            $data[$key]['info'][] = ['id'=>$zszciItem['name'], 'text'=>$item];
                        }
                    }
                }
            }
        }

        //查询倒证订单
        $exData = $exchange->getEnterpriseOrName($result['data']['enterprise_name']);
        $dzData = [];
        foreach ($exData as $keys => &$exDatum) {
            //ddzszcdz
//            $exDatum['leixing'] =  '倒证';

            foreach ($exDatum as $ks =>$items) {
                //如果是获取器数组 则只去text
                if (is_array ($items)){
                    if (isset($items['text'])){
                        $items = $items['text']?:'';
                    }
                }
                $dzData[$keys]['id'] = $exDatum['id'];
                $dzData[$keys]['bh'] = $exDatum['certificate_code'];
                $dzData[$keys]['create_date'] = $exDatum['create_date'];
                $dzData[$keys]['leixing'] = '证书注册倒证';

                if ($ks == 'status'){
                    $dzData[$keys]['status'] = $items;
                }
                foreach ($dzField as $dzItem) {
                    //如果模板字段等于订单详情字段 拼接字段name
                    if ($ks == $dzItem['alias_field_id']){
                        if (!empty($dzItem['name'])){
                            $dzData[$keys]['info'][] = ['id'=>$dzItem['name'],'text'=>$items];
                        }
                    }
                }
            }
        }

        //查询企业证书
        $businessData = $business->getEnterpriseName($result['data']['enterprise_name']);
        $zsblData = [];
        foreach ($businessData as $keyss => &$otDatum) {
            //ddqyzs
//            $datum['leixing'] =  '企业证书';
            foreach ($otDatum as $kss =>$itemss) {
                //如果是获取器数组 则只去text
                if (is_array ($itemss)){
                    if (isset($itemss['text'])){
                        $itemss = $itemss['text']?:'';
                    }
                }
                $zsblData[$keyss]['id'] = $otDatum['id'];
                $zsblData[$keyss]['bh'] = $otDatum['certificate_code'];
                $zsblData[$keyss]['create_date'] = $otDatum['create_date'];
                $zsblData[$keyss]['leixing'] = '企业证书';

                if ($kss == 'status'){
                    $zsblData[$keyss]['status'] = $itemss;
                }
                foreach ($zsblField as $zsblItem) {
                    //如果模板字段等于订单详情字段 拼接字段name
                    if ($kss == $zsblItem['alias_field_id']){
                        if (!empty($zsblItem['name'])){
                            $zsblData[$keyss]['info'][] = ['id'=>$zsblItem['name'],'text'=>$itemss];
                        }
                    }
                }
            }
        }

        $result['orderInfo'] =array_merge ($data,$dzData,$zsblData);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    //添加企业
    public function addEnterprise(
        Request                    $request,
        \app\model\ClueEnterprise  $cent,
        ClueCommunicateRecord      $commRecord,
        ClueMobile                 $mobileModel,
        CluePersonAllocationRecord $allRecord,
        System                     $system,
        UnitInfo $unit,
        WorkPlan $workPlanModel,
        \app\model\UserMessage $userMessageModel,
        CustomField                $customField,
        SystemOperateLog $systemOperateLogModel
    ){
        /**
         * //联系电话
         * @type array $mobArr
         * @param $mobile
         * @param $status
         *
         * //沟通记录
         * @type array $certificate
         * @param $certificate_type
         * @param $certificate_speciality
         * @param $certificate_period_of_validity
         * @param $register
         */
        $param = $request->post();

        $param['f_uid'] = $uid = $request->post('user_login_id');
        $param['is_f'] = 2;//新建默认分配人是自己
//        $param['allocation_date'] = date('Y-m-d H:i:s');//新建默认分配人是自己

        try {
            //拼接省市区详细数据
            if (!empty($param['area'])){
                $areaData = $system->getSuperAreaArray($param['area']);
                if (count ($areaData) == 1){
                    $param['province'] = $areaData[0];
                }else if(count ($areaData) == 2){
                    $param['province'] = $areaData[0];
                    $param['city'] = $areaData[1];
                }
            }

            //企业名称添加企业库
//            if (!empty($param['enterprise_name'])){
//                //注册单位不为空 同步单位到单位资料库
//                $unit->addDataModel ([
//                    'title'=>$param['enterprise_name'],
//                    'type'=>0
//                ]);
//            }else{
//                return ReJson (message::$ERROR_CODE,message::$ERR_ENTER_NAME_EMPTY);
//            }

//            Validate(Enterprise::class)->check($param);
            $mobArr = $param['mobarr'];
            unset($param['mobarr']);

            $param['custom'] = json_encode ($param['custom'],JSON_UNESCAPED_UNICODE);
            $p_id = $cent->addEnterpriseModel($param)->id;

            //沟通记录
            if (isset($param['communicate']) & !empty($param['communicate'])) {
                $communicate = $param['communicate'];

                foreach ($communicate as &$kValue) {
                    Validate(Clue::class)->scene('communicate')->check($kValue);
                    $kValue['clue_p_id'] = $p_id;
                    $kValue['type'] = $this->enterPriseType;

                    //添加计划任务
                    $workPlanModel->addPlanModel([
                        'custom_name'=>$param['enterprise_name'],
                        'plan_date'=>$kValue['next_communicate_date'],
                        'plan_content' =>$kValue['next_plan_content'],
                        'create_uid'=>$param['f_uid'],
                        'type'=>1
                    ]);
                    //添加信息提醒
                    $userMessageModel->addPlanModel($param['enterprise_name'],$param['f_uid'],$uid,'',$kValue['next_communicate_date']);
                }
                $commRecord->addPersonCommunicateRecordModel($communicate);

            }

            //联系电话
            if (isset($mobArr) & !empty($mobArr)) {
                $mobArr = $mobArr;

                foreach ($mobArr as &$iValue) {
//                    Validate(Clue::class)->scene('mobile')->check($iValue);

                    $iValue['clue_p_id'] = $p_id;
                    $iValue['type'] = $this->enterPriseType;

                }
                $mobileModel->addAllPersonMobileModel($mobArr);
            }
            //添加日志
            $allRecord->addPersonAllocationModel($p_id, message::$SUCC_ENTER_PRISE_ADD, $request->param('user_login_id'), $this->enterPriseType);

            $systemOperateLogModel->addOperate ($uid,message::$ENTER,message::$SUCC_ENTER_PRISE_ADD);

        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //修改企业基本信息
    public function editEnterprise(
        Request $request,
        \app\model\ClueEnterprise $cent,
        System $system,
        CustomField $customField,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $request->post();
        $uid = $request->post ('user_login_id');

        if(!$param['area'])
        {
            $param['province'] = $param['city'] = '';
        }else{
            $area_arr = $system->getSuperAreaArray($param['area']);
            $param['province'] = $area_arr[0];
            $param['city'] = $area_arr[1];
        }
        if(isset($param['custom'])){
            //处理自定义字段
            $param['custom'] = $customField->addAndEditCustomFieldHandle($param['custom']);
        }
        try {
            Validate(Enterprise::class)->scene('edit')->check($param);
            $cent->editEnterprise($param);
            //删除redis缓存
            $redisService->delEnterData ($param['id']);
            //添加日志
            $systemOperateLogModel->addOperate ($uid,message::$ENTER,message::$SUCC_ENTER_PRISE_UPDTAE_BASIC);
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //企业联系电话添加
    public function addEnterpriseMobile(
        Request      $request,
        ClueMobile   $mobile,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $paramArr = $request->post('arr');
        $uid = $request->post ('user_login_id');

        try {
            foreach ($paramArr as $value){
                Validate(Clue::class)->scene('mobile')->check($value);

                //查询当前条id是否已经存在数据库
                if (isset($value['id'])){
                    $value['type'] = $this->enterPriseType;
                    $find = $mobile->getIdFindDataModel($value['id']);

                    if (!empty($find)){
                        //存在更新
                        $mobile->editMobileModel ($value);
                    }else{
                        $mobile->addProsonMobileModel($value);
                    }
                }else{
                    $mobile->addProsonMobileModel($value);
                }

                //删除redis缓存
                $redisService->delEnterData ($value['id']);

                //添加日志
                $systemOperateLogModel->addOperate ($uid,message::$ENTER,message::$SUCC_ENTER_INSERT_MOBILE);
            }

        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //联系电话删除
    public function delEnterpriseMobile(
        Request      $request,
        ClueMobile   $mobile,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $id = $request->post('id');
        $uid = $request->post ('user_lgoin_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        try {

            $mobile->delMobileModel($id);
            //删除redis缓存
            $redisService->delEnterData ($id);
            //添加日志
            $systemOperateLogModel->addOperate ($uid,message::$ENTER,message::$SUCC_ENTER_DELETE_MOBILE);
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }


    //联系电话修改
    public function editEnterpriseMobile(
        Request      $request,
        ClueMobile   $mobile,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $id = $request->post('id');
        $uid = $request->post ('user_login_id');

        $param = $request->post();

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        try {
            Validate(Clue::class)->scene('mobile')->check($param);

            $mobile->editMobileModel($param);
            //删除企业缓存
            $redisService->delEnterData ($id);
            //添加日志
            $systemOperateLogModel->addOperate ($uid,message::$ENTER,message::$SUCC_ENTER_UPDATE_MOBILE);

        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //删除企业
    public function delEnterprice(
        Request                            $request,
        ClueCommunicateRecord              $ccmm,
        \app\model\ClueEnterprise          $cent,
        OrderEnterpriseCertificateBusiness $business,
        OrderEnterpriseCertificateRegister $certificateRegister,
        OrderEnterpriseExchange            $reg,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $id = $request->post('id');
        $uid = $request->post ('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        try {
            $data = explode(',', $id);
            if (is_array($data)) foreach ($data as $datum) {

                $result = $cent->getIdInfo($datum);

                /**
                 * 查询该企业是否有关联沟通记录
                 */
                $ccmmData = $ccmm->getPersonComRecordModel($datum, $this->enterPriseType);
                //存在沟通记录，请先删除相关内容
//                if ($ccmmData) {
//                    return ReJson(message::$ERROR_CODE, message::$ERR_ENTERPRISE_DELETE);
//                }

                /**
                 * 查询是否存在企业订单
                 */
                if (!empty($result['enterprise_name'])){ //空名称不验证
                    $busin = $business->getWhereEnterpriseNameModel($result['enterprise_name']);

//                $cerReg = $certificateRegister->getWhereInfoModel($result['enterprise_name']);

                    $exchangeReg = $reg->getWhereInfoModel($result['enterprise_name']);

                    //存在企业订单数据，请先删除相关内容
//                if (!empty($busin) || !empty($cerReg) || !empty($exchangeReg)) {
                    if (!empty($busin) || !empty($exchangeReg)) {
                        return ReJson(message::$ERROR_CODE, message::$ERR_ENTERPRISE_ORDER_DELETE);
                    }

                }

                $cent->delEnterprise($datum);

                $redisService->delEnterData ($id);
                //添加日志
                $systemOperateLogModel->addOperate ($uid,message::$ENTER,message::$SUCC_ENTER_PRISE_DELETE);
            }
        } catch (\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }


        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    /**
     * 获取区域多级联动tree
     */
    public function getAreaTree(System $system)
    {
        $data = Db::table('system_china')->select()->toArray();
        $result = $system->getAreaTree($data);
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }
}